package com.canbot.u05.activity.customvoice

import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.text.TextUtils
import android.view.View

import com.alibaba.fastjson.JSON
import com.canbot.u05.R
import com.canbot.u05.activity.BaseActivityNoTitle
import com.canbot.u05.activity.customvoice.adapter.CustomAudioAdapter
import com.canbot.u05.activity.customvoice.bean.CustomAudioData
import com.canbot.u05.activity.customvoice.tool.GridSpacingItemDecoration
import com.canbot.u05.activity.loge
import com.canbot.u05.activity.setResultCanceled
import com.canbot.u05.activity.setResultOK
import com.canbot.u05.bean.JsonResponse
import com.canbot.u05.socket.IpMsgConst
import com.canbot.u05.socket.MsgSendUtils
import com.canbot.u05.socket.MsgType
import com.canbot.u05.utils.OkHttpUtils
import com.canbot.u05.utils.ToastTools
import com.canbot.u05.widget.LoadingDialogUtils
import kotlinx.android.synthetic.main.activity_choose_audio.*

import java.util.ArrayList
import java.util.Comparator
import java.util.HashMap

/**
 * Created by liu.heng  on 2018/5/24.
 * 自定义对话选择音频
 */
class ChooseAudioActivity : BaseActivityNoTitle(), CustomAudioAdapter.OnItemClickListener {

    private val className = ChooseAudioActivity::class.java.name

    private lateinit var mCustomImageAdapter: CustomAudioAdapter

    private lateinit var mCustomAudioData: MutableList<CustomAudioData>

    private lateinit var dialogLoading: Dialog

    private var voice: String? = null

    private lateinit var audioPath: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_choose_audio)
        val intent = intent
        voice = intent.getStringExtra("voice")
        audioPath = intent.getStringExtra("path")

        initView()
    }

    private fun initView() {

        /**网格布局，每行为3*/
        my_gridView.layoutManager = GridLayoutManager(this, 4)
        my_gridView.addItemDecoration(GridSpacingItemDecoration(4, 120, false))
        getData()

        mCustomImageAdapter = CustomAudioAdapter(this, mCustomAudioData, this)

        my_gridView.adapter = mCustomImageAdapter

    }

    override fun onItemClick(view: View) {
        val i = view.tag as Int
        mCustomImageAdapter.checked = i
        mCustomImageAdapter.notifyDataSetChanged()
        voice = mCustomAudioData[i].path
        val isSuccess = MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, voice)
        loge("$className 播放路径==$voice")
        if (!isSuccess) {
            ToastTools.newInstance(applicationContext).showText(getString(R.string.network_error))
        }
    }

    private fun getData() {
        mCustomAudioData = ArrayList()

        /**http://192.168.12.103:7755/getAudioList*/
        dialogLoading = LoadingDialogUtils.createLoadingDialog(this@ChooseAudioActivity, resources.getString(R.string.request))
        dialogLoading.show()
        val url = "http://" + IpMsgConst.HEAD_SOCKET_HOST + ":7755/getAudioList"
        val hashMap = HashMap<String, String>()
        hashMap["path"] = audioPath
        OkHttpUtils.upLoadFile(url, hashMap, object : OkHttpUtils.OkHttpCallBack {
            override fun onSuccess(result: String) {
                loge("$className $result")
                val strMsgBean = JSON.parseObject(result, JsonResponse::class.java)
                loge("$className onSuccess:" + "http://" + IpMsgConst.HEAD_SOCKET_HOST + ":7755/" + "strMsgBean.getRc()" + strMsgBean.rc)
                if (strMsgBean.rc == 0) {
                    runOnUiThread {
                        dialogLoading.setCancelable(true)
                        dialogLoading.dismiss()
                        val list = JSON.parseArray(strMsgBean.result.toString(), CustomAudioData::class.java)

                        list.sortWith(Comparator { audio, t1 -> audio.name.compareTo(t1.name) })
                        if (list.size > 0) {
                            mCustomAudioData.addAll(list)
                            if (!TextUtils.isEmpty(voice)) {
                                for (i in mCustomAudioData.indices) {
                                    if (voice == mCustomAudioData[i].path) {
                                        mCustomImageAdapter.checked = i
                                        break
                                    }
                                }
                            }
                            mCustomImageAdapter.notifyDataSetChanged()
                        } else {
                            remind_relativeLayout.visibility = View.VISIBLE
                        }
                    }
                }
            }

            override fun onFailure() {
                runOnUiThread {
                    dialogLoading.dismiss()
                    ToastTools.newInstance(applicationContext).showText(this@ChooseAudioActivity.getString(R.string.network_error))
                }
            }
        })
    }

    /**确认*/
    fun nextStep(view: View) {
        loge("$view")
        if (voice.isNullOrEmpty()) {
            ToastTools.newInstance(applicationContext).showText(this@ChooseAudioActivity.getString(R.string.please_select_audio))
            return
        }
        val intent = Intent()
        intent.putExtra("path", voice)
        intent.putExtra("isChecked", true)
        setResultOK(intent)
        finish()
    }

    /**返回*/
    fun back(view: View) {
        loge("$view")
        setResultCanceled()
        finish()
    }

}
